/**
 * Created by tz on 2018/12/27.
 */
import React, { Component } from 'react';
import {Form, Card, Button, Row, Col, Table, Upload, Icon, Popconfirm, Input, Select, Checkbox, message} from 'antd';
import BBSService from '../../service/BBSService';
import UserService from '../../service/UserService';
const uploadButton = (
    <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传照片</div>
    </div>
);
const Option = Select.Option;
export default class BBSEdit extends Component {

    state = {
        title:'BBS新增',
        data:{},
        formItems: [
            {name: '标题', type: 'input', fieldName: 'title'},
            {name: '图片', type: 'img', fieldName: 'images'},
            {name: '内容', type: 'input', fieldName: 'content'},
            {name: '是否置顶', type: 'choice', fieldName: 'topMost'},
        ],
        loading:false,
        error:false,
        //selData:{type:[['BBS','NEWS(单图)'],['THREEIMAGES','THREEIMAGES(三图)']]},
        fileListObj:{images:[]},
        userInfo:{}
    };

    constructor(props) {
        super(props)
    }

    componentDidMount() {
        let id = this.props.match.params.id;
        if(id){
            this.setState({title:'BBS修改'});
            this.fetch(id);
        }else{
            UserService.getProfile().done((res)=>{
                this.state.userInfo = res.entity;
                this.state.data.createStudent = {id:this.state.userInfo.id};
                console.log('this.state.userInfo',this.state.userInfo);
            })
        }
    }

    fetch(id){
        this.setState({
            loading: true
        });
        BBSService.getOne(id).done((res)=>{
            console.log(res.entity);
            this.state.data = res.entity;
            Object.keys(this.state.fileListObj).forEach((item,i)=>{
                if(this.state.data[item]){
                    let pushArr = this.state.data[item].split(',');
                    pushArr.forEach((img,k)=>{
                        this.state.fileListObj[item].push({uid:k,url:img});
                    })

                }
            });
            this.setState({loading: false})
        })
    }

    handleChange(item,fileObj){
        let fileList = fileObj.fileList;
        this.state.fileListObj[item.fieldName] = fileList;
        console.log(fileList);
        this.forceUpdate();
    }

    //页面check
    check(){
        this.state.error = false;

        //标题check
        if (this.state.data.title === null || this.state.data.title === '' || typeof this.state.data.title === 'undefined') {
            this.state.error = true;
            message.error("请输入标题！");
            return
        }
        if (this.state.data.title.length > 255) {
            this.state.error = true;
            message.error("标题最多只能输入255个文字！");
            return
        }

        //内容check
        if (this.state.data.content === null || this.state.data.content === '' || typeof this.state.data.content === 'undefined') {
            this.state.error = true;
            message.error("请输入内容！");
            return
        }
    }

    save(){
        console.log(this.state.data);

        //页面check
        this.check();

        if (this.state.error === false) {
            let imgs = '';
            this.state.fileListObj.images.forEach((item) => {
                if (item.url) {
                    imgs = imgs ? (imgs + ',' + item.url) : (imgs + item.url)
                } else if (item.response && item.status === 'done') {
                    imgs = imgs ? (imgs + ',' + item.response) : (imgs + item.response)
                }
            });
            this.state.data.images = imgs;
            let id = this.props.match.params.id;
            if (id) {
                BBSService.updateOne(this.state.data).done((res) => {
                    console.log(res);
                    this.props.history.goBack();
                })
            } else {
                BBSService.addOne(this.state.data).done((res) => {
                    console.log(res);
                    this.props.history.goBack();
                })
            }
        }
    }
    //页面渲染
    render() {
        return (
            <Card title={this.state.title}>
                <Form>
                    {this.state.formItems.map((item,i)=>{
                        if(item.type==='input'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Input placeholder={"请输入"+item.name} value={this.state.data[item.fieldName]} onChange={(e)=>{
                                        this.state.data[item.fieldName] = e.target.value;
                                        this.forceUpdate();
                                    }}/>
                                </Form.Item>
                            )
                        }else if(item.type==='img'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Upload
                                        key={"upload"+i}
                                        action='/api/upload?path=BBS'
                                        accept='.jpg,.jpeg,.png'
                                        listType='picture-card'
                                        fileList={this.state.fileListObj[item.fieldName]}
                                        //beforeUpload={this.beforeUpload}
                                        //onPreview={this.handlePreview.bind(this)}
                                        headers={{Authorization:('Bearer '+window.sessionStorage.getItem('token'))}}
                                        onChange={this.handleChange.bind(this,item)}
                                    >
                                        {this.state.fileListObj[item.fieldName].length >= 3 ? null : uploadButton}
                                    </Upload>
                                </Form.Item>
                            )
                        }else if(item.type==='select'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Select placeholder={"请选择" + item.name}
                                            value={this.state.data[item.fieldName]}
                                            onChange={(e)=>{
                                                this.state.data[item.fieldName] = e;
                                                this.forceUpdate();
                                            }}
                                    >
                                        {this.state.selData[item.fieldName].map((item1, j) => {
                                            return (
                                                <Option key={'o_' + j} value={item1[0]}>{item1[1]}</Option>
                                            )
                                        })}
                                    </Select>
                                </Form.Item>
                            )
                        }else if(item.type==='choice'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Checkbox checked={this.state.data[item.fieldName]} onChange={(e)=>{
                                        this.state.data[item.fieldName] = e.target.checked;
                                        this.forceUpdate();
                                    }}/>
                                </Form.Item>
                            )
                        }
                    })}
                    <Form.Item>
                        <Popconfirm placement="top" okText="确认" cancelText="关闭" title="是否确定保存?" onConfirm={() =>{
                            this.save();
                        }}>
                            <Button type="primary" icon="save">保存</Button>
                        </Popconfirm>

                    </Form.Item>
                </Form>
            </Card>
        );
    }
}